package com.njworkorder.Aspect;

import com.njworkorder.Annotation.CustomCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class CustomCacheAspect {

    private final RedisTemplate<Object, Object> redisTemplate;
    public CustomCacheAspect(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Around("@annotation(customCache)")
    public Object cacheMethod(ProceedingJoinPoint joinPoint, CustomCache customCache) throws Throwable {
        String cacheName = customCache.cacheNames();
        String keyExpression = customCache.key();
        long ttl = customCache.ttl();
        TimeUnit timeUnit = customCache.timeUnit();

        // 解析SpEL表达式获取实际的key
        String key = parseKey(keyExpression, joinPoint);
        String cacheKey = cacheName + ":" + key;

        // 先从缓存获取
        Object cachedValue = redisTemplate.opsForValue().get(cacheKey);
        if (cachedValue != null) {
            return cachedValue;
        }

        // 缓存未命中，执行原方法
        Object result = joinPoint.proceed();
        if (result != null) {
            // 存入缓存，并设置过期时间
            redisTemplate.opsForValue().set(cacheKey, result, ttl, timeUnit);
        }

        return result;
    }

    private String parseKey(String keyExpression, ProceedingJoinPoint joinPoint) {
        // 实现SpEL表达式解析，获取实际的key值
        // 这里简化处理，实际需要使用SpEL表达式解析器
        return keyExpression;
    }
}